//@ts-ignore
import * as echarts from '../../components/ec-canvas/echarts';
// pages/detail/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    hisData: [],
    hisPageNum: 1,
    hisActiveIndex: 0,
    hisDataTotal: 0,
    warnData: [],
    warnActiveIndex: 0,
    warnDataTotal: 0,
    lazyEc: {
      lazyLoad: true
    },
    lazyComponent: null,
    active: 0,
    activeDevId: null,
    dataList: []
  },
  changeDev(e: any) {
    const id = e.target.dataset.id
    const item = e.target.dataset.item
    console.log(id)
    console.log(item)

    const lazyComponent = this.selectComponent('#lazy-echart-pie')
    const his = item.runState?.his
    const chartData: { value: any; itemStyle: { color: string; }; }[] = []
    let currentIndex = 0
    console.log('his',his)
    his.forEach((item: any) => {
      const cIndex = Math.round((item.startPos + item.endPos) / 2)

      // if (item.startPos <= currentIndex && item.endPos >= currentIndex) {
      let color = '#696969'
      if (item.level == 1) color = '#008000'
      if (item.level == 2) color = '#FFFF00'
      if (item.level == 0) color = '#696969'
      if (item.level == 3) color = '#8B0000'
      if (item.level == 4) color = '#000'
      chartData[cIndex] = ({
        value: item.value,
        itemStyle: {
          color
        }
      })
      currentIndex++
      // }
    })
    //@ts-ignore
    lazyComponent?.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      canvas.setChart(chart);

      // this.lazyChart = chart;

      var option = {
        xAxis: {
          type: 'category',
          minInterval: 0,
          interval: 0,
          data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
        },
        yAxis: {
          show: false
          // type: 'value'
        },
        series: [
          {
            data: chartData,
            type: 'bar'
          }
        ]
      };
      chart.setOption(option);
      return chart;
    });

    this.setData({
      activeDevId: id,
      data: item
    })

    setTimeout(() => {
      this.initWarning()
      this.initHis()
    }, 0)
  },
  setHisIndex(e: any) {
    const { index } = e.currentTarget.dataset
    this.setData({
      hisActiveIndex: index === this.data.hisActiveIndex ? null : index
    })
  },
  setWarnIndex(e: any) {
    const { index } = e.currentTarget.dataset
    this.setData({
      warnActiveIndex: index === this.data.warnActiveIndex ? null : index
    })
  },
  onNavChange(event: any) {
    // event.detail 的值为当前选中项的索引
    if (event.detail === 0) {
      this.init()
    } if (event.detail === 1) {
      this.initHis()
    } if (event.detail === 2) {
      this.initWarning()
    }
    this.setData({ active: event.detail });
  },
  init() {
    wx.request({
      url: 'https://yyapi.lvseguanjia.cn/api-hulk/device/states',
      header: {
        Authorization: `Bearer ${wx.getStorageSync('token')}`,
      },
      data: {
        page: 1,
        size: 25,
        access_token: wx.getStorageSync('token'),
        // orgId: 90
      },
      fail: err => {
        console.log('err', err)
      },
      success: (res: any) => {
        console.log('res', res)
        if (res.data.resp_code != 200) {
          wx.removeStorageSync('token')
          wx.redirectTo({
            url: '../index/index'
          })
          return
        }
        //@ts-ignore
        const data = res?.data?.data.data[0]
        const dataList = res?.data?.data.data
        if (!this.data.activeDevId) {
          this.setData({
            data,
            activeDevId: data.id
          })
        }
        this.setData({
          dataList,
        })

        const his = data.runState?.his
        const chartData: { value: any; itemStyle: { color: string; }; }[] = []
        let currentIndex = 0
        console.log('his', his)
        his.forEach((item: any) => {
          const cIndex = Math.round((item.startPos + item.endPos) / 2)
          console.log(cIndex)
          // if (item.startPos <= currentIndex && item.endPos >= currentIndex) {
          let color = '#696969'
          if (item.level == 1) color = '#008000'
          if (item.level == 2) color = '#FFFF00'
          if (item.level == 0) color = '#696969'
          if (item.level == 3) color = '#8B0000'
          if (item.level == 4) color = '#000'
          chartData[cIndex] = ({
            value: item.value,
            itemStyle: {
              color
            }
          })
          currentIndex++
          // }
        })
        const lazyComponent = this.selectComponent('#lazy-echart-pie')
        //@ts-ignore
        lazyComponent.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          canvas.setChart(chart);

          // this.lazyChart = chart;

          var option = {
            xAxis: {
              type: 'category',
              minInterval: 0,
              interval: 0,
              data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
            },
            yAxis: {
              show: false
              // type: 'value'
            },
            series: [
              {
                data: chartData,
                type: 'bar'
              }
            ]
          };
          chart.setOption(option);
          return chart;
        });

        setTimeout(() => {
          this.initWarning()
          this.initHis()
        }, 0)
      }
    })
  },
  initHis(page: number = 1) {
    if (typeof page !== 'number') {
      page = 1
    }
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: 'https://yyapi.lvseguanjia.cn/api-hulk/dtu/his/list',
      header: {
        Authorization: `Bearer ${wx.getStorageSync('token')}`,
      },
      data: {
        page,
        size: 100,
        access_token: wx.getStorageSync('token'),
        target: 'device',
        dtuId: (this.data.data as any).dtuId,
        deviceId: (this.data.data as any).id,
        dtuIndex: (this.data.data as any).dtuIndex,
      },
      success: (res: any) => {
        //@ts-ignore
        let data
        if (page !== 1) {
          data = this.data.hisData.concat(res?.data?.data.data)
        } else {
          data = res?.data?.data.data
        }
        this.setData({
          hisData: data,
          hisDataTotal: res?.data?.data.totalSize
        })
      },
      complete: () => {
        wx.hideLoading()
        this.setData({
          hisPageNum: page
        })
      }
    })
  },
  initWarning(page: number = 1) {
    if (typeof page !== 'number') {
      page = 1
    }
    function convertSecondsToHours(seconds: any) {
      let hours = (seconds / 3600000);  // 将秒数转换为整数小时
      // return hours
      return Math.floor(hours * 10) / 10;
    }

    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: 'https://yyapi.lvseguanjia.cn/api-hulk/dtuErrInfo/list',
      header: {
        Authorization: `Bearer ${wx.getStorageSync('token')}`,
      },
      data: {
        page: 1,
        size: 100,
        access_token: wx.getStorageSync('token'),
        buss: 'smoke',
        dtuId: (this.data.data as any).dtuId,
        channelIdx: 2
      },
      success: (res: any) => {
        //@ts-ignore
        let data
        if (page !== 1) {
          data = this.data.warnData.concat(res?.data?.data.data)
        } else {
          data = res?.data?.data.data
        }
        data = data?.map((item: any) => {
          item.hours = convertSecondsToHours(item.duration)
          return item
        })
        this.setData({
          warnData: data,
          warnDataTotal: res?.data?.data.totalSize
        })

      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.init()
    // this.initHis()
    // this.initWarning()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('reachbottom')
    if (this.data.active === 1) {
      if (this.data.hisData.length >= this.data.hisDataTotal) return
      this.initHis(this.data.hisPageNum + 1)
    }
    if (this.data.active === 2) {
      if (this.data.warnData.length >= this.data.warnDataTotal) return
      this.initWarning(this.data.hisPageNum + 1)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '油烟监控',
      path: 'pages/detail/index'
    }
  }
})